//
//  WatchBridge.cpp
//  client
//
//  Created by DuanHongbo on 16/3/15.
//
//

#include "WatchBridge.hpp"

#ifdef __cplusplus
extern "C" {
#endif
#include "tolua++.h"
#ifdef __cplusplus
}
#endif

#include "tolua_fix.h"
#include "LuaBasicConversions.h"

#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS)
WatchBridge* WatchBridge::getInstance()
{
    static WatchBridge _instance;
    return &_instance;
}
#endif

static int tolua_watchbridge_getInstance(lua_State* L)
{
    WatchBridge* tolua_ret = (WatchBridge*)  WatchBridge::getInstance();
    tolua_pushusertype(L,(void*)tolua_ret,"WatchBridge");
    return 1;
}

static int tolua_watchbridge_sendPair(lua_State* L)
{
    int argc = 0;
    WatchBridge* cobj = nullptr;
    
    cobj = (WatchBridge*)tolua_tousertype(L,1,0);
    argc = lua_gettop(L)-1;
    if (argc == 2)
    {
        std::string key;
        if(tolua_iscppstring(L,2,0,nullptr)){
            key = tolua_tocppstring(L,2,nullptr);
        }
        
        tolua_Error error;
        if(tolua_isnumber(L,3,0,&error)){
            double value = tolua_tonumber(L, 3, 0);
            cobj->sendPair(key,value);
        }
        else if(tolua_isstring(L,3,0,&error)){
            std::string value = tolua_tocppstring(L,3,nullptr);
            cobj->sendPair(key, value);
        }

        return 0;
    }
    luaL_error(L, "%s has wrong number of arguments: %d, was expecting %d \n", "WatchBridge:sendPair",argc, 2);
    return 0;
}


TOLUA_API int register_watchbridge(lua_State* L)
{
    tolua_open(L);

    //tolua_module(L,"custom",0);
    //tolua_beginmodule(L,"custom");
    
    tolua_usertype(L,"WatchBridge");
    tolua_cclass(L,"WatchBridge","WatchBridge","cc.Ref",nullptr);
    tolua_beginmodule(L,"WatchBridge");
        tolua_function(L,"getInstance",tolua_watchbridge_getInstance);
        tolua_function(L,"sendPair",tolua_watchbridge_sendPair);
    tolua_endmodule(L);
    
    std::string typeName = typeid(WatchBridge).name();
    g_luaType[typeName] = "WatchBridge";
    g_typeCast["WatchBridge"] = "WatchBridge";
    
    //tolua_endmodule(L);
    return 0;
}
